package com.huanxing.cloud.mall.api.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huanxing.cloud.common.core.constant.CommonConstants;
import com.huanxing.cloud.mall.api.mapper.GoodsAppraiseMapper;
import com.huanxing.cloud.mall.api.mapper.OrderInfoMapper;
import com.huanxing.cloud.mall.api.mapper.UserInfoMapper;
import com.huanxing.cloud.mall.api.service.IGoodsAppraiseService;
import com.huanxing.cloud.mall.api.utils.HxTokenHolder;
import com.huanxing.cloud.mall.common.entity.GoodsAppraise;
import com.huanxing.cloud.mall.common.entity.OrderInfo;
import com.huanxing.cloud.mall.common.entity.UserInfo;
import com.huanxing.cloud.security.handler.HxBusinessException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品评价
 *
 * @author lijx
 * @since 2022/3/7 14:18
 */
@Service
@AllArgsConstructor
public class GoodsAppraiseServiceImpl extends ServiceImpl<GoodsAppraiseMapper, GoodsAppraise>
		implements IGoodsAppraiseService {

	private final UserInfoMapper userInfoMapper;

	private final OrderInfoMapper orderInfoMapper;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean add(List<GoodsAppraise> listGoodsAppraise) {
		UserInfo userInfo = userInfoMapper.selectById(HxTokenHolder.getMallUserId());
		listGoodsAppraise.forEach(goodsAppraise -> {
			goodsAppraise.setUserId(userInfo.getId());
			goodsAppraise.setAvatarUrl(userInfo.getAvatarUrl());
			goodsAppraise.setNickName(userInfo.getNickName());
		});
		if (!this.saveBatch(listGoodsAppraise)) {
			throw new HxBusinessException("发表评论失败");
		}
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setId(listGoodsAppraise.get(0).getOrderId());
		orderInfo.setAppraiseStatus(CommonConstants.YES);
		if (orderInfoMapper.updateById(orderInfo) < 1) {
			throw new HxBusinessException("发表评论失败");
		}
		return Boolean.TRUE;
	}

}
